package ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.DoTheWorkSelectAdapter;
import adapter.GridImageAdapter;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.ListOfPapersBean;
import bean.QuestionBean;
import jp.wasabeef.richeditor.RichEditor;
import student.andlei.com.student.R;
import utils.GsonUtils;
import utils.StringUtils;
import utils.log.LogUtil;
import view.BottomAnswerPopWindow;
import view.ConfirmPopWindow;
import view.LinePathView;

/**
 * 强化练习
 */
public class StrengtheningPracticeActivity extends BaseNetActivity{
    private int maxSelectNum = 3;
    private TextView tv_numbr,
            tv_time,
//            tv_answersheet,
            tv_scrappaper;
    private TextView tv_typename;
    private RichEditor tv_content;
    private CheckBox check_shoucang;
    private ImageView check_pen,
            check_rubber;
    private List<ListOfPapersBean.mList.Questions.Options> optionsList = new ArrayList<>();
    private DoTheWorkSelectAdapter selectAdapter;
    private RecyclerView recy_xuanze;
    private RelativeLayout layout_kong;
    private LinearLayout layout_pen,
            layout_rubber,
            layout_wacom;
    //private List<String> list;
    private RecyclerView gv;
    private GridImageAdapter adapter;
    private ImageView img_left,
            img_right,
            img_clean;
    private Button bt_lookanswer;
    private ScrollView scrollView;
    private LinePathView paletteView;
    //private ImageView img_wacom;
    private List<ListOfPapersBean.mList.Questions> mLists = new ArrayList<>();
    private View layoutview;
    private int question_id;
    private int check_type;//1:收藏（默认） 2:取消收藏
    private String drawing_board_image = "";//手写板图片
    private String answer_image;//上传图片

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("强化练习");
        setBaseBack(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        if (baseBean.code == 200) {
            if (action.equals("Book/practice")) {
                mLists  =  GsonUtils.getInstance(context).parseHaveHeaderJArray(baseBean,ListOfPapersBean.mList.Questions.class,"list");
                if(mLists.size()<=0){
                    layout_kong.setVisibility(View.VISIBLE);
                }else {
                    layout_kong.setVisibility(View.GONE);
                    updateUi(i);
                }

            }  else if (action.equals("Task/collectQuestion")) {
                if (check_type == 1) {
                    mLists.get(i).is_favorite = 1;
                    check_shoucang.setChecked(true);
                    check_shoucang.setText("  已收藏");
                } else {
                    mLists.get(i).is_favorite = 0;
                    check_shoucang.setChecked(false);
                    check_shoucang.setText("  未收藏");
                }
            }
        } else {
            if (action.equals("Task/collectQuestion")) {
                if (check_shoucang.isChecked()) {
                    check_shoucang.setChecked(false);
                } else {
                    check_shoucang.setChecked(true);
                }
            }
            toast(baseBean.getMsg());
        }
    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
        if(action.equals("Book/practice")){
            layout_kong.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected int getLayoutId() {
        layoutview = View.inflate(context, R.layout.activity_strengthening_practice, null);
        return R.layout.activity_strengthening_practice;
    }

    @SuppressLint("Range")
    @Override
    protected void findViews() {
        tv_numbr = getView(R.id.tv_number);
        tv_time = getView(R.id.tv_time);
        layout_kong = getView(R.id.layout_kong);
        check_shoucang = getView(R.id.check_shoucang_);
        bt_lookanswer = getView(R.id.bt_lookanswer);
//        tv_answersheet = getView(R.id.tv_answersheet);
        tv_scrappaper = getView(R.id.tv_Scrappaper);
        tv_typename = getView(R.id.tv_answertype);
        tv_content = getView(R.id.tv_content);
        check_pen = getView(R.id.check_pen);
        check_rubber = getView(R.id.check_rubber);
        recy_xuanze = getView(R.id.rycl_xuanze);
        // img_wacom = getView(R.id.img_wacom);
        layout_wacom = getView(R.id.layout_wacom);
        layout_pen = getView(R.id.layout_pen);
        layout_rubber = getView(R.id.layout_rubber);
        img_clean = getView(R.id.img_clean);
        scrollView = getView(R.id.scrollView);
        paletteView = getView(R.id.plt_wacom);
        img_left = getView(R.id.img_left);
        img_right = getView(R.id.img_right);
        gv = getView(R.id.grid_view);
    }

    private void initImagePicker() {
        GridLayoutManager manager = new GridLayoutManager(context, 6, GridLayoutManager.VERTICAL, false);
        gv.setLayoutManager(manager);
        adapter = new GridImageAdapter(context, onAddPicClickListener,false);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        gv.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() <= 0) {
                    return;
                }
                LocalMedia media = selectList.get(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片
                        PictureSelector.create(StrengtheningPracticeActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
                        break;
                }
            }
        });
    }

    @Override
    protected void formatViews() {
//        tv_answersheet.setOnClickListener(this);
        layout_kong.setOnClickListener(this);
        tv_scrappaper.setOnClickListener(this);
        img_clean.setOnClickListener(this);
        img_left.setOnClickListener(this);
        img_right.setOnClickListener(this);
        check_pen.setOnClickListener(this);
        check_rubber.setOnClickListener(this);
        check_shoucang.setOnClickListener(this);
        bt_lookanswer.setOnClickListener(this);

        layout_pen.setBackgroundResource(R.color.check_color);
        initImagePicker();
        paletteView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    //mLists.get(i).shouxieimg = paletteView.getBitMap();
                    if (mLists.size() > 0) {
                        String mpath = "/sdcard/dskqxt/pic/" + mLists.get(i).paper_question_id + ".jpg";
                        //String mpath = App.getAppCacheDir(DoTheWorkActivity.this) + mLists.get(i).paper_question_id + ".jpg";
                        //"/sdcard/dskqxt/pic/"
                        try {
                            paletteView.save(mpath, paletteView.getBitMap());
                            mLists.get(i).shouxieimg = mpath;
                            LogUtil.app("----->手写板对象已赋值");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    scrollView.requestDisallowInterceptTouchEvent(false);
                } else {
                    //不允许ScrollView截断点击事件，点击事件由子View处理
                    scrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
    }

    @Override
    protected void formatData() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recy_xuanze.setLayoutManager(layoutManager);
        selectAdapter = new DoTheWorkSelectAdapter(R.layout.item_work_select, optionsList);
        recy_xuanze.setAdapter(selectAdapter);
        selectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < optionsList.size(); i++) {
                    if (position == i) {
                        optionsList.get(i).setIsSelect(1);
                        //optionsList.get(i).isSelect = 1;
                    } else {
                        optionsList.get(i).setIsSelect(0);
                        //optionsList.get(i).isSelect = 0;
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
        tv_numbr.setText((i + 1) + "/" + mLists.size() + "题");
        loadDataList();
    }

    private void loadDataList() {
        Map<String, String> map = new HashMap<>();
        map.put("question_id", "" + question_id);
        post("Book/practice", map, BaseBean.class, false);
    }

    private void checkTogglet() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "" + check_type);
        map.put("question_id", "" + mLists.get(i).question_id);
        post("Task/collectQuestion", map, BaseBean.class, true);
    }

//    private void loadData(String paper_question_id, String answer_id) {
//        Map<String, String> map = new HashMap<>();
//        map.put("paper_question_id", "" + paper_question_id);
//        map.put("answer_id", "" + answer_id);
//        post("Task/getQuestion", map, BaseBean.class, false);
//    }

    @Override
    protected void getBundle(Bundle bundle) {
        question_id = bundle.getInt("question_id");
    }


    private int i = 0;

    @SuppressLint("Range")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //向左按钮
            case R.id.img_left:
                if (i <= 0) {
                    //toast("已是第一题");
                    return;
                }
                leftorRight();
                i--;
                paletteView.clear();
                updateUi(i);
                break;
            //向右按钮
            case R.id.img_right:
                if (i >= mLists.size() - 1) {
                    //toast("已是最后一题");
                    return;
                }
                leftorRight();
                i++;
                paletteView.clear();
                updateUi(i);
                break;
            //画笔
            case R.id.check_pen:
                //toast("画笔");
                paletteView.setPenColor(Color.BLACK);
                paletteView.setPaintWidth(5);
                // paletteView.setMode(PaletteView.Mode.DRAW);
                layout_pen.setBackgroundResource(R.color.check_color);
                layout_rubber.setBackgroundResource(R.color.uncheck_color);
                break;
            //橡皮
            case R.id.check_rubber:
                //toast("橡皮");
                paletteView.setPenColor(Color.WHITE);
                paletteView.setPaintWidth(50);
                // paletteView.setMode(PaletteView.Mode.ERASER);
                layout_rubber.setBackgroundResource(R.color.check_color);
                layout_pen.setBackgroundResource(R.color.uncheck_color);
                break;
            //清除手写板按钮
            case R.id.img_clean:
                //toast("清除手写板按钮");
                paletteView.clear();
                String mpath = "/sdcard/dskqxt/pic/" + mLists.get(i).paper_question_id + ".jpg";
                try {
                    paletteView.save(mpath, paletteView.getBitMap());
                    mLists.get(i).shouxieimg = "";
                    LogUtil.app("----->手写板对象已赋值");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            //草稿本
            case R.id.tv_Scrappaper:
                new ConfirmPopWindow(this).showAtBottom(layoutview);
                break;
            //答题卡
            case R.id.tv_answersheet:
                break;
            //收藏按钮
            case R.id.check_shoucang_:
                //1:收藏（默认） 2:取消收藏
                if (check_shoucang.isChecked()) {
                    check_type = 1;
                } else {
                    check_type = 2;

                }
                checkTogglet();
                break;
            case R.id.layout_kong:
                loadDataList();
                break;
            //查看答案
            case R.id.bt_lookanswer:
                String slore ="";
                for(QuestionBean.Lore lore : mLists.get(i).lore){
                    slore+=lore.lore_content+",";
                }
                new BottomAnswerPopWindow(this, "", ""+mLists.get(i).answer, ""+mLists.get(i).analysis, ""+slore).showAtBottom(layoutview);
                break;
        }
    }

    private void leftorRight() {
        if (mLists.size() > 0) {
            drawing_board_image = mLists.get(i).shouxieimg;
        }
    }

    private void updateUi(int i) {
        tv_numbr.setText((i + 1) + "/" + mLists.size() + "题");
        tv_typename.setText("(" + mLists.get(i).type_name + ")");
        tv_content.setHtml(mLists.get(i).question_content);
        tv_content.setInputEnabled(false);
        tv_content.setInitialScale(200);
        optionsList = mLists.get(i).question_options;
        selectAdapter.setNewData(optionsList);
        if (mLists.get(i).is_favorite == 0) {
            check_shoucang.setChecked(false);
            check_shoucang.setText("  未收藏");
        } else {
            check_shoucang.setChecked(true);
            check_shoucang.setText("  已收藏");
        }
        Log.i("imglist--->", "" + mLists.get(i).imglist);
        if (mLists.get(i).imglist != null && mLists.get(i).imglist.size() > 0) {
            adapter.setList(mLists.get(i).imglist);
            adapter.notifyDataSetChanged();
        } else {
            List<LocalMedia> mediaList = new ArrayList<>();
            adapter.setList(mediaList);
            adapter.notifyDataSetChanged();
        }
        if (!StringUtils.isNull(mLists.get(i).shouxieimg)) {
            if (mLists.get(i).shouxieimg.contains("http")) {
                Log.i("shouxieimg", i + "-----" + mLists.get(i).shouxieimg);
                loadImageSimpleTarget(mLists.get(i).shouxieimg);
            } else {
                Bitmap bmp = BitmapFactory.decodeFile(mLists.get(i).shouxieimg);//filePath
                Drawable drawable = new BitmapDrawable(bmp);
                paletteView.setBackground(drawable);
            }
        }
        //1.单选题，2.多选题，3.判断题，4.填空题，5.解答题，6.实验题，7.作文题
        switch (mLists.get(i).type_id) {
            case 1:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 2:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 3:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 4:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
            case 5:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
            case 6:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
            case 7:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
            default:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
//                    PictureFileUtils.deleteCacheDirFile(MainActivity.this);
                    // postMultiPhoto(selectList);
                    mLists.get(i).imglist = new ArrayList<LocalMedia>();
                    mLists.get(i).imglist.addAll(selectList);
                    //= selectList;
                    Log.i("imglist--->", "" + mLists.get(i).imglist);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 不需要的api可以不写
            PictureSelector.create(StrengtheningPracticeActivity.this)
                    .openGallery(PictureMimeType.ofImage())
                    .theme(R.style.picture_default_style)
                    .maxSelectNum(maxSelectNum)
                    .minSelectNum(1)
                    .selectionMode(PictureConfig.MULTIPLE)
                    .previewImage(true)
                    .isCamera(true)
                    .enableCrop(false)
                    .compress(true)
                    .glideOverride(160, 160)
                    .previewEggs(true)
                    .withAspectRatio(1, 1)
                    .hideBottomControls(false)
                    .isGif(true)
                    .freeStyleCropEnabled(false)
                    .circleDimmedLayer(false)
                    .showCropFrame(false)
                    .showCropGrid(false)
                    .openClickSound(false)
                    .selectionMedia(selectList)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };

    private void loadImageSimpleTarget(String str) {
        Glide.with(context).asBitmap().load(str).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(final Bitmap resource, Transition<? super Bitmap> transition) {
                Drawable drawable = new BitmapDrawable(resource);
                Log.i("shouxieimg", i + "-----" + resource+"----"+paletteView);
                //setBackgroundDrawable
                //paletteView.setBackgroundDrawable(drawable);
                paletteView.setBackground(drawable);
            }
        });
    }
}
